<template>
  <view :class="['container', `theme-${currentTheme}`]">
    <!-- 联系人基本信息 -->
    <ContactInfo 
      :contact="contact" 
      :contactId="contactId" 
      @update:contact="onContactUpdate"
    />

    <!-- 往来统计 -->
    <view class="stats-section">
      <view class="stats-title">往来统计</view>
      <view class="stats-grid">
        <view class="stats-item">
          <text class="stats-value">¥{{ totalReceive }}</text>
          <text class="stats-label">收礼总额</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">¥{{ totalGive }}</text>
          <text class="stats-label">送礼总额</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">{{ recordCount }}</text>
          <text class="stats-label">往来次数</text>
        </view>
      </view>
    </view>

    <!-- 往来记录 -->
    <view class="records-section">
      <view class="section-header">
        <text class="section-title">往来记录</text>
        <view class="add-record" @tap="showAddRecordModal = true">
          <text class="add-icon">+</text>
          <text class="add-text">添加记录</text>
        </view>
      </view>
      
      <view class="record-list">
        <view v-if="records.length === 0" class="empty-tip">
          暂无往来记录
        </view>
        <view v-else v-for="record in records" :key="record.id" class="record-item" @tap="navigateToGiftBook(record.giftBookId)">
          <view class="record-info">
            <text class="record-type" :class="record.type">{{ getRecordTypeText(record.type) }}</text>
            <text class="record-date">{{ formatDate(record.createTime) }}</text>
          </view>
          <view class="record-detail">
            <view class="record-main">
              <text class="record-amount">¥{{ record.amount || 0 }}</text>
              <text class="record-giftbook" v-if="getGiftBookTitle(record.giftBookId)">{{ getGiftBookTitle(record.giftBookId) }}</text>
            </view>
            <view class="record-sub">
              <text class="record-gift" v-if="record.giftName">{{ record.giftName }}</text>
              <text class="record-remark">{{ record.remarks || '无备注' }}</text>
            </view>
          </view>
          <view class="record-arrow">
            <text class="arrow-icon">›</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-btn delete" @tap="handleDelete">删除</view>
    </view>

    <!-- 添加记录弹窗 -->
    <AddRecordModal
      :show="showAddRecordModal"
      :contactId="contactId"
      :contactName="contact?.name || ''"
      @close="showAddRecordModal = false"
      @submit="handleAddRecord"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad as uniOnLoad, onShow as uniOnShow } from '@dcloudio/uni-app';
import { useContactStore } from '@/store/modules/contact';
import { useCategoryStore } from '@/store/modules/category';
import { useGiftBookStore } from '@/store/modules/giftbook';
import { useThemeStore, ThemeType } from '@/store/modules/theme';
import { Contact } from '@/types';
import { GiftRecord, GiftRecordType, GiftBook } from '@/types/giftbook';
import useThemeMixin from '@/mixins/themeMixin';
import ContactInfo from './components/ContactInfo.vue';
import AddRecordModal from './components/AddRecordModal.vue';
import { nanoid } from '@/utils/nanoid-polyfill';

const contactStore = useContactStore();
const categoryStore = useCategoryStore();
const giftBookStore = useGiftBookStore();
const themeStore = useThemeStore();

// 使用主题 mixin
useThemeMixin();

// 当前主题
const currentTheme = computed(() => themeStore.currentTheme);

const contactId = ref<string>('');
const contact = ref<Contact | null>(null);

// 添加记录弹窗显示状态
const showAddRecordModal = ref(false);

// 处理联系人信息更新
const onContactUpdate = (updatedContact: Contact) => {
  console.log('【联系人详情】联系人信息已更新:', updatedContact);
  contact.value = updatedContact;
};

// 获取记录类型文本
const getRecordTypeText = (type: GiftRecordType | string) => {
  interface TypeMap {
    [key: string]: string;
  }
  
  const typeMap: TypeMap = {
    [GiftRecordType.RECEIVE]: '收礼',
    [GiftRecordType.GIVE]: '送礼',
    [GiftRecordType.OTHER]: '其他'
  };
  return typeMap[type] || '其他';
};

// 格式化日期
const formatDate = (timestamp: number | string) => {
  const date = new Date(timestamp);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 计算属性
const records = computed(() => {
  console.log('【联系人详情】从礼簿获取记录，联系人ID:', contactId.value);
  return giftBookStore.getContactRecords(contactId.value);
});

const totalReceive = computed(() => {
  return giftBookStore.getContactReceiveAmount(contactId.value).toFixed(2);
});

const totalGive = computed(() => {
  return giftBookStore.getContactGiveAmount(contactId.value).toFixed(2);
});

const recordCount = computed(() => {
  return giftBookStore.getContactRecordCount(contactId.value);
});

// 获取礼簿标题
const getGiftBookTitle = (giftBookId: string) => {
  if (!giftBookId) return '';
  const giftBook = giftBookStore.getAllGiftBooks.find((book: GiftBook) => book.id === giftBookId);
  return giftBook ? giftBook.title : '';
};

// 处理添加记录
const handleAddRecord = (recordData: any) => {
  console.log('【联系人详情】添加记录:', recordData);
  try {
    // 确保记录有 ID
    const recordToAdd = {
      ...recordData,
      id: nanoid()
    };
    
    // 使用正确的方法添加记录到礼簿
    giftBookStore.addGiftRecord(recordData.giftBookId, recordToAdd);
    
    // 更新礼簿金额映射
    giftBookStore.updateAmountMaps();
    
    // 关闭弹窗
    showAddRecordModal.value = false;
    
    // 显示成功提示
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('【联系人详情】添加记录失败:', error);
    uni.showToast({
      title: '添加失败',
      icon: 'error'
    });
  }
};

// 删除联系人
const handleDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个联系人吗？删除后不会影响该联系人的礼簿记录数据。',
    success: async (res) => {
      if (res.confirm) {
        try {
          await contactStore.deleteContact(contactId.value);
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'error'
          });
        }
      }
    }
  });
};

// 跳转到礼簿详情页
const navigateToGiftBook = (giftBookId: string) => {
  if (!giftBookId) {
    uni.showToast({
      title: '礼簿信息不完整',
      icon: 'none'
    });
    return;
  }
  
  console.log('【联系人详情】跳转到礼簿详情页, 礼簿ID:', giftBookId);
  
  // 检查礼簿是否存在
  const giftBook = giftBookStore.getAllGiftBooks.find((book: GiftBook) => book.id === giftBookId);
  if (!giftBook) {
    uni.showToast({
      title: '礼簿不存在或已删除',
      icon: 'none'
    });
    return;
  }
  
  // 设置当前礼簿并跳转
  giftBookStore.setCurrentGiftBook(giftBook);
  uni.navigateTo({
    url: `/pages/giftbook/detail?id=${giftBookId}`
  });
};

// 处理页面加载
const handleLoad = async (options: any) => {
  console.log('【联系人详情】handleLoad执行，参数:', options);
  
  try {
    // 先加载数据，确保store中有数据
    await loadAllData();
    
    // 获取ID参数，首先从options中获取
    let id = options?.id;
    
    // 如果options中没有，尝试从当前页面获取
    if (!id) {
      try {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        // @ts-ignore - 不同平台的page对象属性可能不同
        id = currentPage?.options?.id || currentPage?.$page?.options?.id || '';
        console.log('【联系人详情】通过getCurrentPages获取ID:', id);
      } catch (error) {
        console.error('【联系人详情】获取页面参数失败:', error);
      }
    }
    
    if (id) {
      console.log('【联系人详情】获取到联系人ID:', id);
      contactId.value = id;
      refreshContactData();
    } else {
      console.error('【联系人详情】没有联系人ID参数');
      showErrorAndGoBack('参数错误');
    }
  } catch (error) {
    console.error('【联系人详情】页面加载错误:', error);
    showErrorAndGoBack('加载错误');
  }
};

// 加载所有必要数据
const loadAllData = async () => {
  try {
    console.log('【联系人详情】开始加载数据...');
    await Promise.all([
      contactStore.loadContacts(),
      giftBookStore.loadFromStorage(),
      categoryStore.loadCategories(),
      themeStore.initTheme()
    ]);
    
    console.log('【联系人详情】所有数据加载完成');
    
    // 更新礼簿金额映射
    giftBookStore.updateAmountMaps();
    console.log('【联系人详情】礼簿金额映射更新完成');
    
    return true;
  } catch (error) {
    console.error('【联系人详情】加载数据失败:', error);
    showErrorAndGoBack('加载数据失败');
    return false;
  }
};

// 刷新联系人数据
const refreshContactData = () => {
  if (!contactId.value) return;
  
  // 获取联系人信息
  const foundContact = contactStore.getContactById(contactId.value);
  console.log('【联系人详情】查找联系人结果:', foundContact);
  
  if (foundContact) {
    contact.value = foundContact;
    console.log('【联系人详情】联系人信息设置成功:', contact.value);
  } else {
    console.error('【联系人详情】联系人不存在，ID:', contactId.value);
    showErrorAndGoBack('联系人不存在');
  }
};

// 显示错误并返回
const showErrorAndGoBack = (message: string) => {
  uni.showToast({
    title: message,
    icon: 'error'
  });
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};

// 使用uni-app的onLoad钩子，这是微信小程序页面参数获取的标准方式
uniOnLoad((options) => {
  console.log('【联系人详情】uni-app onLoad钩子执行，参数:', options);
  
  // 延迟执行，避免可能的TabBar错误
  setTimeout(() => {
    // 调用处理函数
    handleLoad(options);
  }, 100);
});

// 使用uni-app的onShow钩子
uniOnShow(() => {
  console.log('【联系人详情】uni-app onShow钩子执行');
  
  // 处理可能的TabBar错误
  try {
    // 避免TabBar样式设置错误
    uni.hideTabBar({
      animation: false
    });
  } catch (error) {
    console.warn('【联系人详情】hideTabBar操作错误:', error);
  }
  
  if (contactId.value) {
    refreshContactData();
  }
});

defineExpose({
  // 以下方法供页面调用
  onLoad: (options: any) => {
    console.log('【联系人详情】页面调用 onLoad:', options);
    handleLoad(options);
  },
  onShow: () => {
    console.log('【联系人详情】页面调用 onShow');
    if (contactId.value) {
      refreshContactData();
    }
  }
});
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background-color: var(--background-color);
  min-height: 100vh;
  padding-bottom: 120rpx;

  &.theme-wedding {
    --primary-color: #FF4D4F;
    --primary-dark: #FF1F1F;
    --primary-light: #FFE5E5;
  }

  &.theme-funeral {
    --primary-color: #2c3e50;
    --primary-dark: #1a2634;
    --primary-light: #3c546c;
  }

  &.theme-birthday {
    --primary-color: #FF4D4F;
    --primary-dark: #FF1F1F;
    --primary-light: #FFE5E5;
  }

  &.theme-graduation {
    --primary-color: #1890FF;
    --primary-dark: #096DD9;
    --primary-light: #E6F7FF;
  }

  &.theme-business {
    --primary-color: #722ED1;
    --primary-dark: #531DAB;
    --primary-light: #F9F0FF;
  }

  &.theme-housewarming {
    --primary-color: #52C41A;
    --primary-dark: #389E0D;
    --primary-light: #F6FFED;
  }

  &.theme-fullmoon {
    --primary-color: #F759AB;
    --primary-dark: #EB2F96;
    --primary-light: #FFF0F6;
  }

  &.theme-other {
    --primary-color: #13C2C2;
    --primary-dark: #08979C;
    --primary-light: #E6FFFB;
  }
}

.info-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  position: relative;
  
  &:active {
    background-color: #f5f5f5;
  }
  
  .contact-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .contact-name {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-right: 20rpx;
    }
    
    .contact-category {
      font-size: 24rpx;
      color: var(--primary-color);
      background-color: var(--background-color);
      padding: 4rpx 12rpx;
      border-radius: 4rpx;
      margin-right: auto;
    }

    .edit-icon {
      margin-left: 10rpx;
    }
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .info-item {
    .label {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 8rpx;
      display: block;
    }
    
    .value {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.stats-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .stats-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    
    .stats-item {
      text-align: center;
      
      .stats-value {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
        display: block;
      }
      
      .stats-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.records-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .section-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .add-record {
      display: flex;
      align-items: center;
      color: #409eff;
      font-size: 24rpx;
      
      .add-icon {
        font-size: 32rpx;
        margin-right: 4rpx;
      }
    }
  }
  
  .record-list {
    .empty-tip {
      text-align: center;
      color: #999;
      font-size: 28rpx;
      padding: 40rpx 0;
    }
    
    .record-item {
      padding: 24rpx 20rpx;
      margin: 16rpx 0;
      border-radius: 12rpx;
      background-color: #f8f9fa;
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      position: relative;
      
      &:active {
        background-color: #f0f1f2;
      }
      
      .record-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .record-type {
          font-size: 24rpx;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
          
          &.receive {
            color: #67c23a;
            background-color: rgba(103, 194, 58, 0.1);
          }
          
          &.give {
            color: #f56c6c;
            background-color: rgba(245, 108, 108, 0.1);
          }
          
          &.other {
            color: #909399;
            background-color: rgba(144, 147, 153, 0.1);
          }
        }
        
        .record-date {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .record-detail {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        
        .record-main {
          display: flex;
          align-items: baseline;
          gap: 12rpx;
          
          .record-amount {
            font-size: 40rpx;
            font-weight: 600;
            color: #333;
            line-height: 1.2;
          }
          
          .record-giftbook {
            font-size: 26rpx;
            color: #666;
            flex: 1;
          }
        }
        
        .record-sub {
          display: flex;
          align-items: center;
          gap: 16rpx;
          color: #888;
          font-size: 24rpx;
          
          .record-gift {
            background-color: rgba(0, 0, 0, 0.04);
            padding: 2rpx 12rpx;
            border-radius: 4rpx;
          }
          
          .record-remark {
            color: #999;
            flex: 1;
          }
        }
      }
      
      .record-arrow {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        
        .arrow-icon {
          font-size: 36rpx;
          color: #ccc;
        }
      }
    }
  }
}

.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .action-btn {
    flex: 1;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    border-radius: 40rpx;
    margin: 0 10rpx;
    
    &.delete {
      background-color: var(--primary-color);
      color: #fff;
    }
  }
}
</style> 